package cate.game.world.msg;

import cate.game.GameBody;
import cate.game.client.ClientContext;
import cate.game.client.msg.ClientMsg;
import cate.game.client.msg.MsgConfig;
import cate.game.client.msg.MsgInput;
import cate.game.client.msg.id.MsgIdBWorld;
import cate.game.role.Role;
import cate.game.util.ct.CT;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ClientMsg(title = "礼包码使用 の 请求")
public class GiftCodeUseReq implements MsgInput {

    private static long enableTime;

    @NoteField("礼包码")
    public String code;

    @Override
    public void execute(GameBody game, ClientContext cc) {
        h(game, cc.getRole());
    }

    @Override
    public MsgConfig conf() {
        return MsgIdBWorld.GIFT_CODE_USE_REQ;
    }

    public void h(GameBody game, Role role) {
        long now = System.currentTimeMillis();
        if(now < enableTime) {
            long waitMs = enableTime - now;
            game.notice.message(role, "礼包码同学睡眠中...估计" + waitMs/1000 + "秒后会醒来");
            return;
        }

        if(!role.log.isNormalAction("gift-code-use", 3000)) {
            role.getGame().notice.message(role, "操作太频繁，请歇息片刻");
            return;
        }
        role.getWorld().note = "最近一次尝试使用的码是"+this.code;
        long beginTime = System.currentTimeMillis();
        try {
            role.getWorld().giftCode.useCode(code);
        } catch (EcException e) {
            role.getWorld().giftCode.cancelCodeUseHistory(code);
            if(e.exType == EcException.TYPE_IO) {
                enableTime = now + 66_000l;
                game.notice.message(role, "礼包码同学睡眠中...估计几分钟后会醒来");
            } else {
                game.notice.message(role, e);
            }
        } catch (Exception e) {
            game.notice.message(role, e);
            log.error("", e);
        }
        long costTime = System.currentTimeMillis() - beginTime;
        CT.gs(game).addGiftCodeUseTime(costTime);
    }
}
